<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css"
    integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
  <style>
    .wrap {
      width: 80%;
      margin: 20px auto;
    }

    thead {
      background: black;
      color: white;
    }

    /* css 隔行变色 */
    tr:nth-child(odd):hover {
      background: red;
    }

    tr:nth-child(even):hover {
      background: blue;
    }
  </style>
</head>

<body>
  <div class="container">

    <form class="form-horizontal" id="myform">
      <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">邮箱</label>
        <div class="col-sm-10">
          <input type="email" class="form-control" id="email" placeholder="Email">
        </div>
      </div>
      <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" id="password" placeholder="Password">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <label>
            性别
          </label>
          <div class="radio">
            <input type="radio" name="optionsRadios" id="optionsRadios1" value="男" checked>男
          </div>
          <div class="radio">
            <input type="radio" name="optionsRadios" id="optionsRadios2" value="女">女
          </div>
        </div>
      </div>
      <!--  -->
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <label for="">爱好</label>
          <div class="checkbox">
            <label>
              <input type="checkbox" value="0">
              唱歌
            </label>
          </div>
          <div class="checkbox">
            <label>
              <input type="checkbox" value="1">
              跳舞
            </label>
          </div>
          <div class="checkbox">
            <label>
              <input type="checkbox" value="2">
              rap
            </label>
          </div>
          <div class="checkbox">
            <label>
              <input type="checkbox" value="3">
              篮球
            </label>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" id="reg" class="btn btn-primary">注册</button>
        </div>
      </div>
    </form>
    <div id="showTips">
      暂无数据
    </div>
    <!-- 表格部分 -->
    <div class="mytable">
      <table class="table table-condensed">
        <thead>
          <tr>
            <th>编号</th>
            <th>邮箱</th>
            <th>密码</th>
            <th>性别</th>
            <th>爱好</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <!-- <tr>
            <td>编号</td>
            <td>邮箱</td>
            <td>密码</td>
            <td>性别</td>
            <td>爱好</td>
            <td>
              <button class="btn btn-primary">编辑</button>
              <button class="btn btn-danger">删除</button>
            </td>
          </tr> -->
        </tbody>
      </table>
    </div>

  </div>
  <script src="./javascripts/jquery-3.4.1.min.js"></script>
  <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
    integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
    crossorigin="anonymous"></script>
  <script>
    // 表单提交事件
    $("#myform").submit(function () {
      // 爱好数据的准备
      var aihao = []
      $.each($(":checkbox"), function (index, ele) {
        if (ele.checked) {
          aihao.push(ele.value)
        }
      })
      // 添加和修改共同的数据
      var data = {
        email: $("#email").val(),
        password: $("#password").val(),
        sex: $(":radio:checked").val(),
        aihao: JSON.stringify(aihao)
      }
      var action = $("#reg").attr("action")//获取按钮的action属性
      if (action == "update") {//修改
        data.action = "update"
        data._id = editId
      } else {//添加
        data.action = "add"
      }
      // ---------------------------
      if ($("#email").val() && $("#password").val() && $(":radio:checked").val() && aihao.length != 0) {
        $.ajax({
          url: "http://127.0.0.1:3000/users/addAndUpdate",
          type: "post",
          data: data,
          success: function (res) {

            if (res.success == "添加成功") {
              alert("添加成功")
            }
            if (res.success == "修改成功") {//修改成功 修改按钮内容为注册  移除属性
              alert("修改成功")
              $("#reg").html("注册")
              $("#reg").removeAttr("action")
            }
            loadList()
            $("#email").val("");
            $("#password").val("");
          }
        })
      } else {
        alert("不能为空")
      }
      return false
    })
    //渲染列表
    function loadList() {
      $.post("http://127.0.0.1:3000/users/getlist", {}, function (res) {
        console.log(res)
        if (res.length == 0) {
          $("#showTips").show()
          $("table").hide()
        } else {
          $("#showTips").hide()
          $("table").show()
        }
        var str = ''
        $.each(res, function (index, ele) {
          // 爱好的处理
          var arr = JSON.parse(ele.aihao)
          var newarr = []
          $.each(arr, function (index, ele) {
            if (ele == "0") {
              newarr.push("唱歌")
            } else if (ele == "1") {
              newarr.push("跳舞")
            } else if (ele == "2") {
              newarr.push("rap")
            } else if (ele == "3") {
              newarr.push("篮球")
            }
          })
          console.log(newarr)
          // -------------------------------------
          str += `<tr>
              <td>${index + 1}</td>
              <td>${ele.email}</td>
              <td>${ele.password}</td>
              <td>${ele.sex}</td>
              <td>${newarr}</td>
              <td>
                <button class="btn btn-primary" onclick=update(${JSON.stringify(ele)})>编辑</button>
                <button class="btn btn-danger" onclick="del('${ele._id}')">删除</button>
              </td>
            </tr>`
        })
        $("tbody").html(str)
      }, "json")
    }
    loadList()
    // 删除方法
    function del(_id) {
      $.post("http://127.0.0.1:3000/users/del", { _id: _id }, function (res) {
        alert("删除成功")
        loadList();
      })
    }
    var editId = null;
    //点击编辑
    function update(ele) {
      $("#reg").html("确认修改")
      $("#reg").attr("action", "update")
      editId = ele._id;//存储修改_id
      $("#email").val(ele.email)
      $("#password").val(ele.password);
      // 赋值性别
      $(":radio[value=" + ele.sex + "]").prop("checked", true)
      // 赋值爱好
      // 清空爱好
      $(":checkbox").prop("checked", false);
      var arr = JSON.parse(ele.aihao)
      $.each(arr, function (index, ele) {
        $(":checkbox[value=" + ele + "]").prop("checked", true)
      })
    }
    //

  </script>
</body>

</html>